package com.offcn.dao.impl;

import com.offcn.dao.BookDao;
import com.offcn.entity.Book;
import com.offcn.utils.BaseDao;
import com.offcn.utils.Page;

import java.util.List;

public class BookDaoImpl extends BaseDao<Book> implements BookDao {
    //创建一个page对象，方方便后面封装  已知：pageSize,pageno  查询：totalRecord  计算：totalPageNo
    private Page<Book> bookPage = new Page<>();
    int totalPageNo;  //总页数
    int pageSize = bookPage.pageSize;  //每页展示的数据量



    //进入图书管理模块时，查询数据库中的数据，交给前台展示,
    @Override
    public Page<Book> getBookList(Integer pageno) {
        //计算总页数 不能整除就加1
        if(totalRecord()%bookPage.getPageSize()==0){
            totalPageNo = totalRecord()/bookPage.pageSize;
        }else{
            totalPageNo = (totalRecord()/bookPage.pageSize)+1;
        }
        //准备sql语句，进行分页查询  第一个?:每页开始索引(页码-1)*每页数量  第二个：每页存放数量
        String sql = "select * from books limit ?,?";

        List<Book> list = getBeanList(sql, (pageno - 1) * pageSize, pageSize);

        //设置数据
        bookPage.setList(list);
        bookPage.setPageNo(pageno);
//        bookPage.setPageSize(pageSize);
        bookPage.setTotalRecord(totalRecord());

        return bookPage;
    }




    //获取总记录数
    @Override
    public int totalRecord() {
        String sql = "select count(*) from books";
        Long totalRecord = (Long) getSingleValue(sql);
        int record = totalRecord.intValue();
        return record;
    }


    //在修改的时候用于去获取被修改的数据
    @Override
    public Book getBookByID(Integer id) {
        //根据id查询book数据，展示在修改页面
        String sql = "SELECT * FROM books WHERE id=?";
        Book book = getBean(sql, id);
        return book;
    }


    //修改
    @Override
    public void modifyBook(Book book) {
        String sql = "UPDATE books SET title=?,author=?,price=?,sales=?,stock=? WHERE id = ?";
        Object[] o = {book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),book.getId()};
        //更改数据
        update(sql,o);
    }


    //添加数据
    @Override
    public void addBook(Book book) {
        String sql = "INSERT INTO books (title,author,price,sales,stock,img_path) VALUES(?,?,?,?,?,'path')";
        Object[] o = {book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock()};
        update(sql,o);
    }


    //删除功能
    @Override
    public void deleteBookById(Integer id) {
        String sql = "delete from books where id=?";
        update(sql,id);
    }


/*    public static void main(String[] args) {
        BookDaoImpl bookDao = new BookDaoImpl();
        Book book = new Book(32, "ccc", "cc", 66.0, 533, 266,"aaa");
        bookDao.addBook(book);
    }*/


}
